package com.yk._7ReadWriteLock读写锁;

import java.util.HashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author xuxing
 * @data 2020/4/14
 */

/**
 * 独占锁
 * 共享锁
 *
 * 读-读 可以共存多个线程操作资源
 * 读-写 不可以多个线程操作共享资源
 * 写-写 不可以多个线程操作共享资源
 */
public class _01ReadWriteLock {
    public static void main(String[] args) {
        Resource resource = new Resource();
        for (int i = 0; i < 20; i++) {
            final int temp = i;
            new Thread(()->{
                resource.addElement(String.valueOf(temp)+"_key", String.valueOf(temp)+"_val");
            },"插入线程-"+String.valueOf(i)).start();
        }

        for (int i = 0; i < 20; i++) {
            final int temp = i;
            new Thread(()->{
                resource.getElement(String.valueOf(temp)+"_key");
            },"读取线程-"+String.valueOf(i)).start();
        }
    }
}

class Resource{
    private HashMap<String,String> map = new HashMap();
    private ReadWriteLock lock = new ReentrantReadWriteLock();
    public void addElement(String key,String val){
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在添加元素");
            this.map.put(key, val);
            System.out.println(Thread.currentThread().getName() + "添加成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void getElement(String key){
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正在读取元素");
            System.out.println(this.map.get(key));
            System.out.println(Thread.currentThread().getName() + "读取元素成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }
}
